<template>
    <div class="e-form">
        <BillTop :title="$route.meta.title" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs"></div>
        <div class="tabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
                v-if="auditState.canModify"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="formData"
                                label-width="170px"
                                :rules="rules"
                                ref="ruleForm"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁编号" width="220">
                                            <div style="display: flex">
                                                <el-input
                                                    v-model="formData.tenderApplyNo"
                                                    disabled
                                                ></el-input>
                                                <ComShowBiddingButton
                                                    :tenderId="tenderId"
                                                    mod="hire"
                                                />
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="租赁单位">
                                            <el-input v-model="formData.applyOrgName"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="招标类型">
                                            <span>周材租赁招标</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="关闭日期">
                                            <span>{{ formData.closeDate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁方式">
                                            <span>{{
                                                formData.tenderForm | tenderForm(this)
                                            }}</span>
                                            <!-- <el-select v-model="formData.tenderForm" placeholder="请选择" @change="selectChange($event, '租赁方式')">
                                    <el-option v-for="(item, index) in options.tenderForm" :key="index" :label="item.kvKey" :value="item.kvId">
                                    </el-option>
                                </el-select> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <!-- 传id、名称closeOrgId -->
                                        <el-form-item label="关闭机构">
                                            <span>{{ formData.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="拟租赁项目名称" width="200">
                                            <span>{{ formData.tenderName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="拟租赁金额（元）">
                                            <span>{{ formData.tenderAmount }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item
                                        label="租赁需求陈述/ 租赁项目概况*："
                                        prop="purchaseDemandStatement"
                                    >
                                        <el-input
                                            type="textarea"
                                            :rows="2"
                                            v-model="formData.purchaseDemandStatement"
                                            disabled
                                        >
                                        </el-input>
                                    </el-form-item>
                                </el-row>
                                <el-row>
                                    <el-form-item label="关闭原因：" prop="closeReason">
                                        <el-input
                                            type="textarea"
                                            :rows="2"
                                            v-model="formData.closeReason"
                                        >
                                        </el-input>
                                    </el-form-item>
                                </el-row>
                                <el-row>
                                    <el-col :span="24" style="margin-top: 10px">
                                        <el-form-item label="状态">
                                            <span>{{ formData.state | state(this) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <ComNullify :formData="formData" />
                            </el-form>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <ComAttachIndex
                            bucketName="tender"
                            :relationId="billId"
                            ref="ComAttachIndex"
                            :isView="
                                (auditState.canAudit === false && auditState.canModify === false) ||
                                Object.keys(auditState).length === 0
                            "
                            :key="1"
                            v-if="Object.keys(auditState).length !== 0"
                        />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ComExaHistory :billType="auditParams.billType" ref="ComExaHistory" />
                    </div>
                </div>
            </el-tabs>
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab" v-else>
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="formData"
                                label-width="170px"
                                :rules="rules"
                                ref="ruleForm"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁编号" width="220">
                                            <div style="display: flex">
                                                <span>{{ formData.tenderApplyNo }}</span>
                                                <ComShowBiddingButton
                                                    :tenderId="tenderId"
                                                    mod="hire"
                                                />
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="租赁单位">
                                            <span>{{ formData.applyOrgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="招标类型">
                                            <span>周材租赁招标</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="关闭日期">
                                            <span>{{ formData.closeDate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁方式">
                                            <span>{{
                                                formData.tenderForm | tenderForm(this)
                                            }}</span>
                                            <!-- <el-select v-model="formData.tenderForm" placeholder="请选择" @change="selectChange($event, '租赁方式')">
                                    <el-option v-for="(item, index) in options.tenderForm" :key="index" :label="item.kvKey" :value="item.kvId">
                                    </el-option>
                                </el-select> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <!-- 传id、名称closeOrgId -->
                                        <el-form-item label="关闭机构">
                                            <span>{{ formData.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="拟租赁项目名称" width="200">
                                            <span>{{ formData.tenderName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="拟租赁金额（元）">
                                            <span>{{ formData.tenderAmount }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item
                                        label="租赁需求陈述/ 租赁项目概况*："
                                        prop="purchaseDemandStatement"
                                    >
                                        <span>{{ formData.purchaseDemandStatement }}</span>
                                    </el-form-item>
                                </el-row>
                                <el-row>
                                    <el-form-item label="关闭原因：" prop="closeReason">
                                        <span>{{ formData.closeReason }}</span>
                                    </el-form-item>
                                </el-row>
                                <el-row>
                                    <el-col :span="24" style="margin-top: 10px">
                                        <el-form-item label="状态">
                                            <span>{{ formData.state | state(this) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <ComNullify :formData="formData" />
                            </el-form>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <ComAttachIndex
                            bucketName="tender"
                            :relationId="billId"
                            :isView="
                                (auditState.canAudit === false && auditState.canModify === false) ||
                                Object.keys(auditState).length === 0
                            "
                            ref="ComAttachIndex"
                            :key="2"
                            v-if="Object.keys(auditState).length !== 0"
                        />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ComExaHistory :billType="auditParams.billType" ref="ComExaHistory" />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <ComExaButtons
                :auditState="auditState"
                @exas="exas"
                :routeTo="
                    () => {
                        this.$router.push({
                            path: './hireBiddingApplicationEdit',
                            query: { billid: this.tenderId, seat: 'close' }
                        })
                    }
                "
                :founderId="formData.founderId"
                :state="formData.state"
                :isPrint="false"
            />
            <el-button @click="handleClose">取消</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
// import ComTreeTable from '@/templates/table/treeTable.vue'
// import ComTreeFile from '@/templates/table/treeFile.vue'
// import ComPagination from '@/components/pagination/pagination.vue'
import ComShowBiddingButton from '@/pages/bidding/common/showBiddingButton.vue'
import ComExaButtons from '@/components/common/exaButtons'
import ComAttachIndex from '@/components/common/attachIndex'
import ComExaHistory from '@/components/common/exaHistory.vue'
import ComNullify from '@/pages/bidding/common/nullify.vue'
// import applyCloseRequest from '@/api/tender/applyClose.js'
import materialZhouCaiLeasingRequest from '@/api/tender/materialZhouCaiLeasing.js'
import auditRequest from '@/api/tender/audit.js'
import commonRequest from '@/api/tender/common.js'
import { openAppClient } from '@/utils/common'
import { mapState, mapMutations } from 'vuex'

export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            formData: {},
            test: '',
            selectData: [],
            selectTableColumnAttr: [
                {
                    label: '单据编号',
                    prop: 'billNo'
                },
                {
                    label: '拟招标项目名称',
                    prop: 'tenderName'
                },
                {
                    label: '单据日期',
                    prop: 'gmtCreate'
                },
                {
                    label: '单据机构名称',
                    prop: 'orgName'
                }
            ],
            selectTableColumnWidth: {
                leftWidth: '150',
                rightWidth: '100'
            },
            selectDataPagination: {},
            rules: {
                // purchaseDemandStatement: {
                //     required: true,
                //     message: '请输入租赁需求陈述',
                //     trigger: 'blur'
                // },
                closeReason: [
                    {
                        required: true,
                        message: '请输入关闭原因：',
                        trigger: 'blur'
                    },
                    { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
                ]
            },
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 60252,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            nullifyParams: {
                billId: this.$route.query.billid,
                billType: 60252,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            }
        }
    },
    computed: {
        ...mapState({
            options: state => state.biddingApplication.dictionaries
        }),
        tenderId () {
            return this.formData.tenderApplyId
        },
        billId () {
            return this.$route.query.billId || this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        // ComTreeTable,
        // ComTreeFile,
        // ComPagination,
        ComShowBiddingButton,
        ComExaButtons,
        ComAttachIndex,
        ComExaHistory,
        ComNullify
    },
    async created () {
        // 编辑不用查询招标信息，直接编辑当前billId信息
        await this.getData()
        // 获取审核按钮状态
        this.getCurrentUnitInfo()
    },
    mounted () {
        // 保存所有tabName
        const arr = ['baseInfo', 'attach', 'auditHistory']
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight(arr)
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item)?.offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item)?.offsetTop
                return itemTop
            })
        })
    },
    beforeDestroy () {
        this.$notify.closeAll()
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setSelectedInfo']),
        // 审核相关操作
        async exas (arg, routeTo) {
            if (arg === 'audit') {
                await this.saveAllData(false)
                this.setAuditParams(this.auditParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/exaDialog', '填写审核意见', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    auditRequest.audit(auditParams).then(() => {
                        if (auditParams.isPass) {
                            this.clientPop('suc', '审核成功', routeTo)
                        } else {
                            this.clientPop('suc', '返回修改成功', routeTo)
                        }
                        this.getCurrentUnitInfo()
                        this.getData()
                        this.$refs.ComExaHistory.getAuditHistory()
                    })
                }, null, null, null, 'small')
            } else if (arg === 'undoAudit') {
                this.clientPop('info', '确定要撤回上一步审核操作吗？', () => {
                    auditRequest.undoAudit(this.auditParams).then(() => {
                        this.clientPop('suc', '撤回成功', routeTo)
                        this.getCurrentUnitInfo()
                        this.getData()
                        this.$refs.ComExaHistory.getAuditHistory()
                    })
                })
            } else if (arg === 'submitCommit') {
                this.$refs.ruleForm.validate(async valid => {
                    if (valid) {
                        const promise1 = await this.saveAllData(false)
                        const promise2 = auditRequest.commit(this.auditParams)
                        Promise.all([promise1, promise2]).then(() => {
                            this.clientPop('suc', '保存并提交成功', routeTo)
                            this.getCurrentUnitInfo()
                            this.getData()
                            this.$refs.ComExaHistory.getAuditHistory()
                        })
                    } else {
                        return false
                    }
                })
            } else if (arg === 'submit') {
                this.saveAllData()
            } else if (arg === 'nullify') {
                this.setAuditParams(this.nullifyParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/nullifyDialog', '单据作废原因', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    commonRequest.nullify(auditParams).then(() => {
                        this.clientPop('suc', '作废成功', routeTo)
                        this.getCurrentUnitInfo()
                        this.getData()
                        this.$refs.ComExaHistory.getAuditHistory()
                    })
                }, null, null, null, 'small')
            } else if (arg === 'deleteData') {
                this.deleteData()
            }
        },
        getAuditHistory () {
            auditRequest.getAuditHistory(this.auditParams).then(res => {
                this.$refs.ComExaHistory.tableData = res
                this.$refs.ComExaHistory.pagination.total = res.length
            })
        },
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
                if (this.formData.state === 5) {
                    this.auditState.canModify = false
                }
            })
        },
        deleteData () {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', this.delData)
        },
        onChangeTab (e) {
            const height = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight (arr) {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById(arr[length - 1] + 'Con')) {
                    const lastConHeight = document.getElementById(
                        arr[length - 1] + 'Con'
                    )?.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        delData () {
            materialZhouCaiLeasingRequest.closeDelete({ id: this.billId }).then(() => {
                const callBack = () => {
                    this.$router.push({
                        path: './hireBiddingApplicationEdit',
                        query: { billid: this.tenderId, seat: 'close' }
                    })
                }
                this.clientPop('suc', '删除成功', callBack)
            })
        },
        async getData () {
            await materialZhouCaiLeasingRequest.closeGetById({ id: this.billId }).then(res => {
                this.formData = res
            })
        },
        showBidding () {
            if (!this.tenderId) return // 前期需求可切换，现在不需要
            this.$notify.closeAll()
            this.$notify({
                title: '查看招标详情',
                dangerouslyUseHTMLString: true,
                message: `正式环境：客户端打开新页面<br>
                测试环境：手动打开新页面<br>
                <textarea cols="35" rows="10">http://localhost:8080/biddingApplicationShow?tenderId=${this.tenderId}</textarea>
                `,
                duration: 0
            })
            // this.$router.push({
            //     path: './biddingApplicationShow',
            //     query: { tenderId: this.tenderId }
            // })
        },
        async saveAllData (notice = true) {
            return new Promise((resolve, reject) => {
                // 基础信息验证
                this.$refs.ruleForm.validate(async valid => {
                    if (!valid) {
                        this.onChangeTab({ name: 'baseInfo' })
                        reject()
                        return false
                    }
                })
                // 附件验证
                if (this.$refs.ComAttachIndex.attachTableData.length === 0) {
                    this.onChangeTab({ name: 'attachCon' })
                    this.clientPop('err', '请上传附件')
                    reject()
                    return false
                }
                materialZhouCaiLeasingRequest.closeUpdate(this.formData).then(() => {
                    resolve()
                    if (notice === false) return
                    this.clientPop('suc', '保存成功')
                    // this.$router.push({
                    //     path: './hireBiddingApplicationEdit',
                    //     query: { billid: this.tenderId, seat: 'close' }
                    // })
                })
            })
        },
        getNowDate () {
            // 个位数前补0
            const zeroFill = function (num) {
                if (parseInt(num) < 10) {
                    num = '0' + num
                }
                return num
            }
            let nowtime = new Date()
            nowtime =
                zeroFill(nowtime.getFullYear()) +
                '-' +
                zeroFill(nowtime.getMonth() + 1) +
                '-' +
                zeroFill(nowtime.getDate())
            this.$set(this.formData, 'applyTime', nowtime)
        },
        handleClose () {
            this.$router.push({
                path: './hireBiddingApplicationEdit',
                query: { billid: this.tenderId, seat: 'close' }
            })
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        }
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
